package com.keba.lamp.common.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class ImageUtil {

    /**
     * 合并图片
     * @param imageUrls
     * @return
     * @throws IOException
     */
    public static BufferedImage mergeImages(List<String> imageUrls) throws IOException {
        // 读取所有图片
        List<BufferedImage> images = new ArrayList<>();
        int maxWidth = 0;
        int totalHeight = 0;

        // 计算合并后的图片尺寸
        for (String imagePath : imageUrls) {
            BufferedImage image = ImageIO.read(new URL(imagePath));
            images.add(image);

            maxWidth = Math.max(maxWidth, image.getWidth());
            totalHeight += image.getHeight();
        }

        // 创建合并后的图片
        BufferedImage mergedImage = new BufferedImage(maxWidth, totalHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = mergedImage.createGraphics();

        // 设置背景颜色
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, maxWidth, totalHeight);

        // 绘制所有图片
        int currentHeight = 0;
        for (BufferedImage image : images) {
            g2d.drawImage(image, 0, currentHeight, null);
            currentHeight += image.getHeight();
        }

        // 释放资源
        g2d.dispose();
        return mergedImage;
    }
}
